package com.powergisol.gis.controller;

import cn.hutool.crypto.SecureUtil;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSBuckets;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.powergisol.gis.service.IFileService;
import com.powergisol.gis.util.FileList;
import com.powergisol.gis.util.PropertyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.MongoDbFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Description:
 */
@RestController
@Api(description = "查询mongodb数据接口" ,value = "查询mongodb数据接口")
public class GridsController {
    private static Logger logger = LoggerFactory.getLogger(GridsController.class);
    @Autowired
    private MongoDbFactory mongoDbFactory;

    @Autowired
    private GridFsOperations operations;

    @Autowired
    private IFileService fileService;

//    @Value("${file-url}")
//    private String fileUrl;


    @GetMapping("getFileUrl")
    @ApiOperation(value = "从mongodb中读取数据存在临时文件获取服务的相关属性", notes = "从mongodb中读取数据存在临时文件获取服务的相关属性")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "uuid", value = "uuid", defaultValue = "0", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "serviceName", value = "存储路径", defaultValue = "0", required = true, paramType = "query")
    })
    public String getFileUrl(String serviceName,String uuid){
        logger.info("从mongodb中读取数据存在临时文件获取服务的相关属性={},{}",serviceName,uuid);
        GridFSDownloadStream stream = null;
        String filePath = null;
        try {
            String filename = SecureUtil.md5(uuid+serviceName.replace("/",File.separator));
            GridFSFile file = operations.findOne(new Query(Criteria.where("filename").is(filename)));
            if(file!=null) {
                GridFSBucket bucket = GridFSBuckets.create(mongoDbFactory.getDb());
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                // 获取Mongodb中文件的缓存输出流
                bucket.downloadToStream(file.getId(), baos);
                String userDir = System.getProperty("user.dir");
                userDir = userDir.substring(0,userDir.lastIndexOf(File.separator));
                filePath = userDir+File.separator+"serviceData"+File.separator+"temp"+File.separator+"layer"+File.separator + uuid+".json";
                File outFile = new File(filePath);
                //文件存在则删除
                if(outFile.exists()){
                    outFile.delete();
                }
                if (!outFile.getParentFile().exists()) {
                    outFile.getParentFile().mkdirs();
                }
                FileWriter fw = new FileWriter(outFile.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(baos.toString());
                bw.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (stream != null) stream.close();
        }
        return filePath;
    }
    @GetMapping("delByUuid")
    @ApiOperation(value = "根据uuid删除mongodb中的数据", notes = "根据uuid删除mongodb中的数据")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "uuid", value = "uuid", defaultValue = "0", required = true, paramType = "query")
    })
    public void delByUuid(String uuid){
        logger.info("根据uuid删除mongodb中的数据={}",uuid);
        fileService.delByUuid(uuid);
    }

    @PostMapping("upByMD5")
    @ApiOperation(value = "根据MD5修改mongodb中的数据", notes = "根据MD5修改mongodb中的数据")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "uuid", value = "服务uuid", defaultValue = "0", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "key", value = "存库时的路径，位移标识", defaultValue = "0", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "object", value = "实体对象", defaultValue = "0", required = true, paramType = "query")
    })
    public Boolean upByMD5(String uuid,String key,Object object){
        logger.info("根据MD5修改mongodb中的数据={},{}",uuid,key);
        Boolean flag = fileService.upByMD5(uuid,key,object.toString());
        return flag;
    }



}
